package com.imyuanma.qingyun.lowcode.model.bo;

import com.imyuanma.qingyun.common.util.CollectionUtil;
import com.imyuanma.qingyun.common.util.StringUtil;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 字段查询配置
 *
 * @author wangjy
 * @date 2022/12/24 15:07:14
 */
@Data
public class FieldSearchConfigBO {
    /**
     * 根据哪些字段查询
     */
    private List<String> fieldJavaNameList = new ArrayList<>();
    /**
     * 单条查询, true表示根据字段查询单条, false表示根据字段查询多条数据
     */
    private Boolean selectOneFlag = true;

    /**
     * 查询字段集合, 生成代码时使用, 配置时不用
     */
    private List<GenerateFieldBO> fieldList;

    /**
     * db字段名拼接
     *
     * @return
     */
    public String getFieldDbNameJoinStr() {
        if (CollectionUtil.isNotEmpty(fieldList)) {
            return fieldList.stream().map(GenerateFieldBO::getFieldDbName).collect(Collectors.joining(","));
        }
        return null;
    }

    /**
     * java字段名拼接
     *
     * @return
     */
    public String getFieldJavaNameJoinStr() {
        if (CollectionUtil.isNotEmpty(fieldList)) {
            return fieldList.stream().map(GenerateFieldBO::getFieldJavaName).collect(Collectors.joining(","));
        }
        return null;
    }

    /**
     * 方法名
     *
     * @return
     */
    public String getMethodName() {
        if (CollectionUtil.isNotEmpty(fieldList)) {
            StringBuilder sb = new StringBuilder(Boolean.TRUE.equals(selectOneFlag) ? "getBy" : "getListBy");
            for (GenerateFieldBO fieldBO : fieldList) {
                sb.append(StringUtil.toFirstUpper(fieldBO.getFieldJavaName()));
            }
            return sb.toString();
        }
        return null;
    }

    /**
     * 转换为代码生成时配置
     *
     * @param fieldList
     * @return
     */
    public FieldSearchConfigBO convertForGen(List<GenerateFieldBO> fieldList) {
        FieldSearchConfigBO fieldSearchConfigBO = new FieldSearchConfigBO();
        fieldSearchConfigBO.setFieldJavaNameList(fieldList.stream().map(GenerateFieldBO::getFieldJavaName).collect(Collectors.toList()));
        fieldSearchConfigBO.setSelectOneFlag(this.selectOneFlag);
        fieldSearchConfigBO.setFieldList(fieldList);
        return fieldSearchConfigBO;
    }

    /**
     * 是否有效
     *
     * @return
     */
    public boolean valid() {
        return selectOneFlag != null && CollectionUtil.isNotEmpty(fieldJavaNameList);
    }

    /**
     * 是否有效for生成代码
     *
     * @return
     */
    public boolean genValid() {
        return selectOneFlag != null && CollectionUtil.isNotEmpty(fieldList);
    }

}
